package com.neteast.androidclient.contact.widget;

import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONObject;

import com.neteast.androidclient.contact.Constant;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.activity.MainActivity;
import com.neteast.androidclient.contact.adapter.GroupAdapter;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactData;
import com.neteast.androidclient.contact.domain.ContactRowManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
/**
 * 联系人信息的展示面板
 * @author tiangh
 * 2012-3-15 上午9:30:33
 */
public final class InfoDetailPanel extends RelativeLayout{
	
	
	private Context context;
	private LayoutInflater inflater;
	private RelativeLayout root;
	private TextView topTitle;
	private ImageView contactPhoto;
	private EditText contactName;
	private EditText contactNickname;
	private EditText contactOrganization;
	private EditText contactJob;
	private Button contactGroup;
	private EditText contactRemark;
	private TableLayout rowContainer;
	public Contact contact;
	private ArrayAdapter<String> phoneAdapter;
	private ArrayAdapter<String> emailAdapter;
	private ArrayAdapter<String> imAdapter;
	private ArrayAdapter<String> locationAdapter;
	private GroupAdapter groupAdapter;
	//对原有contact的拷贝，判断是否改变
	private Contact cloneContact;
	private RelativeLayout customType;
	private LinearLayout selectType;
	private PopupWindow groupWindow;
	private RelativeLayout groupContainer;
	
	public InfoDetailPanel(Context c,Contact contact) {
		super(c);
		context=c;
		this.contact=contact;
		inflater = LayoutInflater.from(context);
		root = (RelativeLayout) inflater.inflate(R.layout.contact_panel, null);
		init();
		addView(root);
	}

	private void init() {
		findView();
		initAdapter();
		initView();
		setListener();
	}
	
	private ArrayAdapter<String> createAdapter(ArrayList<String> datas) {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.type_item, datas);
		return adapter;
	}
	
	private void initAdapter() {
		phoneAdapter=createAdapter(MainActivity.phoneTypes);
		emailAdapter =createAdapter(MainActivity.emailTypes);
		imAdapter = createAdapter(MainActivity.imTypes);
		locationAdapter = createAdapter(MainActivity.locationTypes);
		String[] values=new String[]{"东方网信","大学同学","高中同学","北京","河北","初中同学","家人","朋友","同事"};
		groupAdapter = new GroupAdapter(context, new ArrayList<String>(Arrays.asList(values)),contactGroup);
	}
	
	private void findView() {
		topTitle = (TextView) root.findViewById(R.id.top_title);
		contactPhoto = (ImageView) root.findViewById(R.id.contact_photo);
		contactName = (EditText) root.findViewById(R.id.contact_name);
		contactNickname = (EditText) root.findViewById(R.id.contact_nickname);
		contactOrganization = (EditText) root.findViewById(R.id.contact_organization);
		contactJob = (EditText) root.findViewById(R.id.contact_job);
		contactGroup = (Button) root.findViewById(R.id.group);
		contactRemark = (EditText) root.findViewById(R.id.remark_content);
		rowContainer = (TableLayout) root.findViewById(R.id.main_info_container);
	}
	
	private void initView() {
		//设置面板标题，ownId等于自己的contactId
		topTitle.setText(contact.ownId==contact.contactId?
				context.getString(R.string.label_me_title):
				context.getString(R.string.label_contact_title));
		
		//设置姓名
		if (!TextUtils.isEmpty(contact.displayName)) {
			contactName.setText(contact.displayName);
			contactName.setEnabled(false);
		}
		//设置昵称
		if (!TextUtils.isEmpty(contact.nickName)) {
			contactNickname.setText(contact.nickName);
			contactNickname.setEnabled(false);
		}
		//设置公司名
		if (!TextUtils.isEmpty(contact.organization)) {
			contactOrganization.setText(contact.organization);
			contactOrganization.setEnabled(false);
		}
		//设置职位名
		if (!TextUtils.isEmpty(contact.job)) {
			contactJob.setText(contact.job);
			contactJob.setEnabled(false);
		}
		//设置照片
		if (contact.hasPhoto) {
			contactPhoto.setImageBitmap(ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(contact.photo), 120, 120));
		}else {
			Bitmap defaultPhoto = BitmapFactory.decodeResource(context.getResources(), R.drawable.default_photo);
			contactPhoto.setImageBitmap(defaultPhoto);
		}
		contactPhoto.setTag(false);
		//设置电话
		setRows(contact.phones, Constant.MIME_PHONE, phoneAdapter);
		//设置邮件
		setRows(contact.emails, Constant.MIME_EMAIL, emailAdapter);
		//设置im
		setRows(contact.ims, Constant.MIME_IM, imAdapter);
		//设置地址
		setRows(contact.locations, Constant.MIME_LOCATION, locationAdapter);
		//设置群组
		setGroup();
		//设置备注
		if (!TextUtils.isEmpty(contact.remark)) {
			contactRemark.setText(contact.remark);
		}
	}
	private void setRows(ArrayList<ContactData> data,int type,ArrayAdapter<String> adapter){
		customType = (RelativeLayout) inflater.inflate(R.layout.custom_type, null);
		selectType = (LinearLayout) inflater.inflate(R.layout.select_type, null);
		if (data==null) {
			return;
		}
		int size = data.size();
		for(int i=0;i<size;i++){
			LinearLayout row = ContactRowManager.insertNewBlankRow(context, type, rowContainer, adapter,selectType,customType);
			ContactRowManager.fillRowWithContent(row, data.get(i));
		}
	}
	/**
	 * 设置群组
	 * @param groups
	 */
	private void setGroup() {
		groupContainer = (RelativeLayout) inflater.inflate(R.layout.group_layout, null);
		
		ListView groupList = (ListView) groupContainer.findViewById(R.id.group_list);
		groupList.setAdapter(groupAdapter);
		
		groupList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				LinearLayout ll=(LinearLayout) view;
				CheckBox box=(CheckBox) ll.getChildAt(1);
				box.setChecked(!box.isChecked());
				final ArrayList<String> list=GroupAdapter.groupValues;
				int size = list.size();
				StringBuilder sb=new StringBuilder();
				for(int i=0;i<size;i++){
					String v = list.get(i);
					if (!TextUtils.isEmpty(v)) {
						sb.append(v).append(",");
					}
				}
				if (sb.length()>0) {
					sb.deleteCharAt(sb.length()-1);
				}
				contactGroup.setText(sb.toString());
			}
		});
		contactGroup.setText(contact.groups);
		groupAdapter.setCheckedValue(contact.groups);
	}
	
	private void setListener() {
		
		contactGroup.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				groupAdapter.setCheckedValue(contactGroup.getText().toString());
				groupWindow = new PopupWindow(groupContainer, contactGroup.getMeasuredWidth(), 400, true);
				groupWindow.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.bg_dialog));
				groupWindow.showAsDropDown(contactGroup);
			}
		});
	}
	public void openEditState() {
		cloneContact=contact.clone();
		if (!contact.isReadOnly) {
			contactPhoto.setTag(true);
			contactName.setEnabled(true);
			contactNickname.setEnabled(true);
			contactOrganization.setEnabled(true);
			contactJob.setEnabled(true);
			Log.i("test", "open");
		}
		contactRemark.setEnabled(true);
		contactGroup.setEnabled(true);
		groupAdapter.setCheckedValue(contactGroup.getText().toString());
		contact.phones.clear();
		contact.emails.clear();
		contact.ims.clear();
		contact.locations.clear();
		ContactRowManager.setRowsEditable();
		showFirstEditLine(cloneContact.phones, Constant.MIME_PHONE, phoneAdapter);
		showFirstEditLine(cloneContact.emails, Constant.MIME_EMAIL, emailAdapter);
		showFirstEditLine(cloneContact.ims, Constant.MIME_IM, imAdapter);
		showFirstEditLine(cloneContact.locations, Constant.MIME_LOCATION, locationAdapter);
	}
	private void showFirstEditLine(ArrayList<ContactData> datas,int type,ArrayAdapter<String> adapter){
		if (datas.size()==0) {
			ContactRowManager.insertNewBlankRow(context, type, rowContainer, adapter,selectType,customType);
		}
	}
	public void closeEditState() {
		if (!contact.isReadOnly) {
			contactPhoto.setTag(false);
			contactName.setEnabled(false);
			contactNickname.setEnabled(false);
			contactOrganization.setEnabled(false);
			contactJob.setEnabled(false);
			contact.displayName=contactName.getText().toString();
			contact.nickName=contactNickname.getText().toString();
			contact.organization=contactOrganization.getText().toString();
			contact.job=contactJob.getText().toString();
		}
		contactRemark.setEnabled(false);
		contactGroup.setEnabled(false);
		
		contact.remark=contactRemark.getText().toString();
		contact.groups=contactGroup.getText().toString();
		
		ContactRowManager.closeRowsEditable(rowContainer,contact);
		JSONObject jsonObject = ContactRowManager.isContactChanged(cloneContact, contact);
		if (jsonObject!=null) {
			Log.i("test", "json="+jsonObject.toString());
		}
	}
}
